﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Windows;
using InfoService.Enums;
using InfoService.Feeds;
using InfoService.Twitter;
using MediaPortal.Configuration;
using MediaPortal.Dialogs;
using MediaPortal.GUI.Library;
using MediaPortal.Localisation;
using MediaPortal.Profile;

namespace InfoService.Utils
{
    public static class InfoServiceUtils
    {
        private static LocalisationProvider _localizationStrings;
        private static readonly Logger logger = Logger.GetInstance();
        private static bool _localizationLoaded;
        public static void LoadLocalization()
        {
            _localizationLoaded = false;
            //string localizationFile = Config.GetSubFolder(Config.Dir.Language, @"InfoService\strings_en.xml");
            //logger.WriteLog("Try to load localization " + localizationFile, LogLevel.Debug, InfoServiceModul.InfoService);
            string localizationDirectory = Config.GetSubFolder(Config.Dir.Language, "InfoService");
            if (Directory.Exists(localizationDirectory))
            {
                logger.WriteLog("Looking for user language", LogLevel.Debug, InfoServiceModul.InfoService);
                string language = new Settings(Config.GetFile(Config.Dir.Config, "MediaPortal.xml")).GetValueAsString("skin", "language", "English");
                string localizationCultureName = string.Empty;
                if (!string.IsNullOrEmpty(language))
                {   
                    logger.WriteLog("User language is " + language + ". Load localization...", LogLevel.Debug, InfoServiceModul.InfoService);
                    localizationCultureName = GUILocalizeStrings.GetCultureName(language);
                    if (File.Exists(Config.GetSubFolder(Config.Dir.Language, @"InfoService\strings_" + localizationCultureName + ".xml")))
                    {
                        _localizationStrings = new LocalisationProvider(localizationDirectory, localizationCultureName);
                        GUILocalizeStrings.Load(language);
                        _localizationLoaded = true;
                    }
                    else logger.WriteLog("Couldn't found user language " + Config.GetSubFolder(Config.Dir.Language, @"InfoService\strings_" + localizationCultureName + ".xml") + " for InfoService", LogLevel.Error, InfoServiceModul.InfoService);
                }
                else logger.WriteLog("Couldn't get the user language. Didn't found user language from MediaPortal", LogLevel.Error, InfoServiceModul.InfoService);
            }
            else logger.WriteLog("Localization file doesn't exist. Folder " + localizationDirectory + " doesn't exist", LogLevel.Error, InfoServiceModul.InfoService);
        }
        public static string GetLocalizedLabel(int id)
        {
            return _localizationLoaded ? _localizationStrings.GetString("unmapped", id) : string.Empty;
        }
        public static void ShowDialogOkWindow(string header, string text)
        {
            logger.WriteLog("Show dialog window", LogLevel.Info, InfoServiceModul.InfoService);
            GUIDialogOK window = (GUIDialogOK)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_OK);
            window.SetHeading(header);
            List<string> textCol = new List<string>();
            int lastIndex = 0;
            for (int i = 44; i < text.Length; i += 45)
            {
                if (text[i] != ' ' || text[i] != ',' || text[i] != '.')
                {
                    while (i > 1)
                    {
                        i--;
                        if (text[i] == ' ' || text[i] == ',' || text[i] == '.')
                        {
                            break;
                        }
                    }
                }
                textCol.Add(text.Substring(lastIndex, i - lastIndex));
                lastIndex = i;
            }
            textCol.Add(text.Substring(lastIndex, text.Length - lastIndex));
            for (int i = 0; i < textCol.Count; i++) textCol[i] = textCol[i].Trim();
            for (int i = 1; i <= 4; i++)
            {
                if (i <= textCol.Count) window.SetLine(i, textCol[i - 1]);
            }
            window.FlowDirection = FlowDirection.RightToLeft;
            window.DoModal(GUIWindowManager.ActiveWindow);

        }
        public static void SetProperty(string property, string value)
        {
            GUIPropertyManager.SetProperty(property, value);
            if(GUIPropertyManager.Changed) logger.WriteLog("Set property \"" + property + "\" to \"" + value + "\" successful", LogLevel.Debug, InfoServiceModul.InfoService);
            else logger.WriteLog("Set property \"" + property + "\" to \"" + value + "\" failed", LogLevel.Warning, InfoServiceModul.InfoService);
        }
        public static void InitAllProperties()
        {
            logger.WriteLog("Init all properties", LogLevel.Debug, InfoServiceModul.InfoService);
            InfoServiceUtils.SetProperty("#infoservice.weather.enabled", "false");
            InfoServiceUtils.SetProperty("#infoservice.weather.location", " ");
            InfoServiceUtils.SetProperty("#infoservice.weather.today.temp", " ");
            InfoServiceUtils.SetProperty("#infoservice.weather.today.feelsliketemp", " ");
            InfoServiceUtils.SetProperty("#infoservice.weather.today.humidity", " ");
            InfoServiceUtils.SetProperty("#infoservice.weather.today.uvindex", " ");
            InfoServiceUtils.SetProperty("#infoservice.weather.today.condition", " ");
            InfoServiceUtils.SetProperty("#infoservice.weather.today.sunrise", " ");
            InfoServiceUtils.SetProperty("#infoservice.weather.today.sunset", " ");
            InfoServiceUtils.SetProperty("#infoservice.weather.today.wind", " ");
            InfoServiceUtils.SetProperty("#infoservice.weather.today.mintemp", " ");
            InfoServiceUtils.SetProperty("#infoservice.weather.today.maxtemp", " ");
            InfoServiceUtils.SetProperty("#infoservice.weather.today.img.small.fullpath", " ");
            InfoServiceUtils.SetProperty("#infoservice.weather.today.img.small.filenamewithext", " ");
            InfoServiceUtils.SetProperty("#infoservice.weather.today.img.small.filenamewithoutext", " ");
            InfoServiceUtils.SetProperty("#infoservice.weather.today.img.big.fullpath", " ");
            InfoServiceUtils.SetProperty("#infoservice.weather.today.img.big.filenamewithext", " ");
            InfoServiceUtils.SetProperty("#infoservice.weather.today.img.big.filenamewithoutext", " ");
            InfoServiceUtils.SetProperty("#infoservice.weather.today.weekday", " ");
            InfoServiceUtils.SetProperty("#infoservice.weather.lastupdated.message", " ");
            InfoServiceUtils.SetProperty("#infoservice.weather.lastupdated.datetime", " ");


            for (int daynum = 2; daynum <= 6; daynum++)
            {
                InfoServiceUtils.SetProperty("#infoservice.weather.day" + daynum + ".mintemp", " ");
                InfoServiceUtils.SetProperty("#infoservice.weather.day" + daynum + ".maxtemp", " ");
                InfoServiceUtils.SetProperty("#infoservice.weather.day" + daynum + ".sunrise", " ");
                InfoServiceUtils.SetProperty("#infoservice.weather.day" + daynum + ".sunset", " ");
                InfoServiceUtils.SetProperty("#infoservice.weather.day" + daynum + ".day.condition", " ");
                InfoServiceUtils.SetProperty("#infoservice.weather.day" + daynum + ".night.condition", " ");
                InfoServiceUtils.SetProperty("#infoservice.weather.day" + daynum + ".day.wind", " ");
                InfoServiceUtils.SetProperty("#infoservice.weather.day" + daynum + ".night.wind", " ");
                InfoServiceUtils.SetProperty("#infoservice.weather.day" + daynum + ".day.humidity", " ");
                InfoServiceUtils.SetProperty("#infoservice.weather.day" + daynum + ".night.humidity", " ");
                InfoServiceUtils.SetProperty("#infoservice.weather.day" + daynum + ".day.img.small.fullpath", " ");
                InfoServiceUtils.SetProperty("#infoservice.weather.day" + daynum + ".day.img.small.filenamewithext", " ");
                InfoServiceUtils.SetProperty("#infoservice.weather.day" + daynum + ".day.img.small.filenamewithoutext", " ");
                InfoServiceUtils.SetProperty("#infoservice.weather.day" + daynum + ".day.img.big.fullpath", " ");
                InfoServiceUtils.SetProperty("#infoservice.weather.day" + daynum + ".day.img.big.filenamewithext", " ");
                InfoServiceUtils.SetProperty("#infoservice.weather.day" + daynum + ".day.img.big.filenamewithoutext", " ");
                InfoServiceUtils.SetProperty("#infoservice.weather.day" + daynum + ".night.img.small.fullpath", " ");
                InfoServiceUtils.SetProperty("#infoservice.weather.day" + daynum + ".night.img.small.filenamewithext", " ");
                InfoServiceUtils.SetProperty("#infoservice.weather.day" + daynum + ".night.img.small.filenamewithoutext", " ");
                InfoServiceUtils.SetProperty("#infoservice.weather.day" + daynum + ".night.img.big.fullpath", " ");
                InfoServiceUtils.SetProperty("#infoservice.weather.day" + daynum + ".night.img.big.filenamewithext", " ");
                InfoServiceUtils.SetProperty("#infoservice.weather.day" + daynum + ".night.img.big.filenamewithoutext", " ");
                InfoServiceUtils.SetProperty("#infoservice.weather.day" + daynum + ".weekday", " ");
            }
            InfoServiceUtils.SetProperty("#infoservice.feed.enabled", "false");
            InfoServiceUtils.SetProperty("#infoservice.feed.isalltitles", "false");
            InfoServiceUtils.SetProperty("#infoservice.feed.selected.itemimg", " ");
            InfoServiceUtils.SetProperty("#infoservice.feed.selected.title", " ");
            InfoServiceUtils.SetProperty("#infoservice.feed.titles", InfoServiceUtils.GetLocalizedLabel(24));
            InfoServiceUtils.SetProperty("#infoservice.feed.alltitles", InfoServiceUtils.GetLocalizedLabel(24));
            InfoServiceUtils.SetProperty("#infoservice.feed.selected.feed", " ");
            InfoServiceUtils.SetProperty("#infoservice.feed.selected.type", " ");
            InfoServiceUtils.SetProperty("#infoservice.feed.selected.index", " ");
            InfoServiceUtils.SetProperty("#infoservice.feed.selected.description", " ");
            InfoServiceUtils.SetProperty("#infoservice.feed.itemcount", " ");
            InfoServiceUtils.SetProperty("#infoservice.feed.img", GUIGraphicsContext.Skin + @"\media\InfoService\defaultFeedAll.png");
            InfoServiceUtils.SetProperty("#infoservice.feed.separator", " ");
            InfoServiceUtils.SetProperty("#infoservice.feed.lastupdated.message", " ");
            InfoServiceUtils.SetProperty("#infoservice.feed.lastupdated.datetime", " ");
            InfoServiceUtils.SetProperty("#infoservice.twitter.enabled", "false");
            InfoServiceUtils.SetProperty("#infoservice.twitter.messages", InfoServiceUtils.GetLocalizedLabel(24));
            InfoServiceUtils.SetProperty("#infoservice.twitter.separator", " ");
            InfoServiceUtils.SetProperty("#infoservice.twitter.itemcount", " ");
            InfoServiceUtils.SetProperty("#infoservice.twitter.lastupdated.message", " ");
            InfoServiceUtils.SetProperty("#infoservice.twitter.lastupdated.datetime", " ");
            InfoServiceUtils.SetProperty("#infoservice.twitter.selected.username", " ");
            InfoServiceUtils.SetProperty("#infoservice.twitter.selected.userpicture", " ");
            InfoServiceUtils.SetProperty("#infoservice.twitter.selected.timeline", " ");
            RecentlyAddedUtils.LoadLastRecentlyAddedItems();
        }
        public static string GetTimeDifferenceToNow(DateTime datetime)
        {
            //logger.WriteLog("Calc time difference", LogLevel.Debug, InfoServiceModul.InfoService);
            if (datetime.Date != new DateTime())
            {
                TimeSpan diff = (DateTime.Now - datetime);
                if (diff.TotalSeconds >= 1)
                {
                    if (diff.TotalSeconds >= 1 && diff.TotalSeconds < 60)
                    {
                        return string.Format(GetLocalizedLabel(20), (int)diff.TotalSeconds);
                    }
                    if (diff.TotalMinutes < 60 && diff.TotalMinutes >= 1)
                    {
                        return string.Format(GetLocalizedLabel(21), (int)diff.TotalMinutes);
                    }
                    if (diff.TotalHours < 24 && diff.TotalHours >= 1)
                    {
                        return string.Format(GetLocalizedLabel(22), (int)diff.TotalHours, diff.Minutes);
                    }
                    if (diff.TotalDays >= 1)
                    {
                        return string.Format(GetLocalizedLabel(23), (int)diff.TotalDays, diff.Hours, diff.Minutes);
                    }
                }
            }
            logger.WriteLog("Cannot calc time difference. Feed item has no Date/Time", LogLevel.Warning, InfoServiceModul.InfoService);
            return "";
        }

        public static bool ShowKeyboard(int window, ref string sString)
        {
            logger.WriteLog("Show keyboard", LogLevel.Info, InfoServiceModul.InfoService);
            VirtualKeyboard keyboard = (VirtualKeyboard)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_VIRTUAL_KEYBOARD);
            if (null == keyboard)
            {
                return false;
            }
            keyboard.IsSearchKeyboard = false;
            keyboard.Reset();
            keyboard.Text = sString;
            keyboard.DoModal(window);
            if (keyboard.IsConfirmed)
            {
                sString = keyboard.Text;
            }
            return keyboard.IsConfirmed;
        }
        public static void DeleteTwitterCache()
        {
            logger.WriteLog("Try to delete twitter cache", LogLevel.Info, InfoServiceModul.Twitter);
            using (Settings settings = new Settings(Config.GetFile(Config.Dir.Config, "MediaPortal.xml")))
            {
                DateTime lastdeletion;
                if (!DateTime.TryParse(settings.GetValueAsString("InfoService", "TwitterLastCacheDeletion", ""), out lastdeletion))
                {
                    settings.SetValue("InfoService", "TwitterLastCacheDeletion", DateTime.Today.ToShortDateString());
                    logger.WriteLog("Couldn't parse last twitter cache deletion date. Set last twitter cache deletion to now", LogLevel.Warning, InfoServiceModul.Twitter);
                }
                else
                {
                    if (TwitterService.DeletionInterval == DeleteCache.Day &&
                        DateTime.Today.Subtract(lastdeletion).Days >= 1 && DateTime.Today.Subtract(lastdeletion).Days < 7)
                    {
                        logger.WriteLog("Time to delete twitter cache after 1 day", LogLevel.Debug, InfoServiceModul.Twitter);
                        TwitterService.DeleteCache();
                        settings.SetValue("InfoService", "TwitterLastCacheDeletion", DateTime.Today.ToShortDateString());
                    }
                    else if (FeedService.DeletionInterval == DeleteCache.Week &&
                             DateTime.Today.Subtract(lastdeletion).Days >= 7 && DateTime.Today.Subtract(lastdeletion).Days < 30)
                    {
                        logger.WriteLog("Time to delete twitter cache after 1 week", LogLevel.Debug, InfoServiceModul.Twitter);
                        TwitterService.DeleteCache();
                        settings.SetValue("InfoService", "TwitterLastCacheDeletion",
                                          DateTime.Today.ToShortDateString());
                    }
                    else if (FeedService.DeletionInterval == DeleteCache.Month &&
                             DateTime.Today.Subtract(lastdeletion).Days >= 30)
                    {
                        logger.WriteLog("Time to delete twitter cache after 1 month", LogLevel.Debug, InfoServiceModul.Twitter);
                        TwitterService.DeleteCache();
                        settings.SetValue("InfoService", "TwitterLastCacheDeletion",
                                          DateTime.Today.ToShortDateString());
                    }
                    else logger.WriteLog("It's not the time to delete twitter cache", LogLevel.Info, InfoServiceModul.Twitter);
                }
            }
        }
        public static void DeleteFeedCache()
        {
            logger.WriteLog("Try to delete feed cache", LogLevel.Info, InfoServiceModul.Feed);
            using (Settings settings = new Settings(Config.GetFile(Config.Dir.Config, "MediaPortal.xml")))
            {
                DateTime lastdeletion;
                if (!DateTime.TryParse(settings.GetValueAsString("InfoService", "FeedLastCacheDeletion", ""), out lastdeletion))
                {
                    logger.WriteLog("Couldn't parse last feed cache deletion date. Set last feed cache deletion to now", LogLevel.Warning, InfoServiceModul.Feed);
                    settings.SetValue("InfoService", "FeedLastCacheDeletion", DateTime.Today.ToShortDateString());
                }
                else
                {
                    if (FeedService.DeletionInterval == DeleteCache.Day &&
                        DateTime.Today.Subtract(lastdeletion).Days >= 1 && DateTime.Today.Subtract(lastdeletion).Days < 7)
                    {
                        logger.WriteLog("Time to delete feed cache after 1 day", LogLevel.Debug, InfoServiceModul.Feed);
                        FeedService.DeleteCache();
                        settings.SetValue("InfoService", "FeedLastCacheDeletion", DateTime.Today.ToShortDateString());
                    }
                    else if (FeedService.DeletionInterval == DeleteCache.Week &&
                             DateTime.Today.Subtract(lastdeletion).Days >= 7 && DateTime.Today.Subtract(lastdeletion).Days < 30)
                    {
                        logger.WriteLog("Time to delete feed cache after 1 week", LogLevel.Debug, InfoServiceModul.Feed);
                        FeedService.DeleteCache();
                        settings.SetValue("InfoService", "FeedLastCacheDeletion", DateTime.Today.ToShortDateString());
                    }
                    else if (FeedService.DeletionInterval == DeleteCache.Month &&
                             DateTime.Today.Subtract(lastdeletion).Days >= 30)
                    {
                        logger.WriteLog("Time to delete feed cache after 1 month", LogLevel.Debug, InfoServiceModul.Feed);
                        FeedService.DeleteCache();
                        settings.SetValue("InfoService", "FeedLastCacheDeletion",
                                          DateTime.Today.ToShortDateString());
                    }
                    else logger.WriteLog("It's not the time to delete feed cache", LogLevel.Info, InfoServiceModul.Feed);
                }
            }
        }
        public static void InitLog()
        {
            using (Settings settings = new Settings(Config.GetFile(Config.Dir.Config, "MediaPortal.xml")))
            {
                Logger.LogFile = Config.GetFile(Config.Dir.Log, "infoservice.log");
                Logger.LogDebug = settings.GetValueAsBool("InfoService", "LogDebug", false);
                Logger.LogWarning = settings.GetValueAsBool("InfoService", "LogWarning", true);
                Logger.LogError = settings.GetValueAsBool("InfoService", "LogError", true);
            }
        }
    }
}
